package com.kkb.mybatis.framework.handler;

import com.kkb.mybatis.framework.config.BoundSql;
import com.kkb.mybatis.framework.config.Configuration;
import com.kkb.mybatis.framework.config.MappedStatement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

/**
 * 处理preparedStatement对象
 */
public class PreparedStatementHandler implements StatementHandler {

    private ParameterHandler parameterHandler;
    private ResultSetHandler resultSetHandler;

    public PreparedStatementHandler(Configuration configuration) {
        this.parameterHandler = configuration.newParameterHandler();
        this.resultSetHandler = configuration.newResultSetHandler();
    }

    @Override
    public Statement prepare(String sql, Connection connection) throws Exception {
        return connection.prepareStatement(sql);
    }

    @Override
    public void parameterize(Object param, Statement statement, BoundSql boundSql) throws Exception {
        PreparedStatement preparedStatement = (PreparedStatement) statement;
        parameterHandler.setParameters(param, preparedStatement, boundSql);
    }

    @Override
    public List<Object> query(Statement statement, MappedStatement mappedStatement) throws Exception {
        PreparedStatement preparedStatement = (PreparedStatement) statement;
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Object> list = resultSetHandler.handleResultSet(resultSet, preparedStatement, mappedStatement);
        return list;
    }
}
